import { createApp, h, App } from 'vue'
import Toast from '@/components/common/Toast.vue'

interface ToastOptions {
  message: string
  type?: 'success' | 'error' | 'info' | 'warning'
  duration?: number
}

interface ToastInstance {
  app: App
  container: HTMLElement
}

// Toast 实例队列
const toastInstances: ToastInstance[] = []

// 清理所有 Toast
function clearAllToasts() {
  toastInstances.forEach(({ app, container }) => {
    try {
      app.unmount()
      if (container.parentNode) {
        container.parentNode.removeChild(container)
      }
    } catch (error) {
      console.error('清理 Toast 失败:', error)
    }
  })
  toastInstances.length = 0
}

export function showToast(options: ToastOptions) {
  const { message, type = 'info', duration = 3000 } = options

  // 如果已经有太多 Toast（超过 3 个），清理旧的
  if (toastInstances.length >= 3) {
    const oldInstance = toastInstances.shift()
    if (oldInstance) {
      try {
        oldInstance.app.unmount()
        if (oldInstance.container.parentNode) {
          oldInstance.container.parentNode.removeChild(oldInstance.container)
        }
      } catch (error) {
        console.error('清理旧 Toast 失败:', error)
      }
    }
  }

  // 创建容器
  const container = document.createElement('div')
  document.body.appendChild(container)

  // 创建 Vue 应用实例
  const app = createApp({
    render() {
      return h(Toast, {
        message,
        type,
        duration,
        show: true,
        onClose: () => {
          console.log('[toast.ts] onClose 触发，准备移除 Toast')
          // 关闭后移除
          setTimeout(() => {
            try {
              console.log('[toast.ts] 开始 unmount 和移除 DOM')
              app.unmount()
              if (container.parentNode) {
                container.parentNode.removeChild(container)
              }
              // 从队列中移除
              const index = toastInstances.findIndex(t => t.container === container)
              if (index > -1) {
                toastInstances.splice(index, 1)
              }
              console.log('[toast.ts] Toast 清理完成，当前队列长度:', toastInstances.length)
            } catch (error) {
              console.error('移除 Toast 失败:', error)
            }
          }, 300)
        }
      })
    }
  })

  console.log('[toast.ts] 创建 Toast:', message, 'duration:', duration)
  app.mount(container)

  // 添加到队列
  toastInstances.push({ app, container })
  console.log('[toast.ts] Toast 添加到队列，当前队列长度:', toastInstances.length)
}

export const toast = {
  success: (message: string, duration = 3000) => {
    showToast({ message, type: 'success', duration })
  },
  error: (message: string, duration = 3000) => {
    showToast({ message, type: 'error', duration })
  },
  info: (message: string, duration = 3000) => {
    showToast({ message, type: 'info', duration })
  },
  warning: (message: string, duration = 3000) => {
    showToast({ message, type: 'warning', duration })
  },
  clear: () => {
    clearAllToasts()
  }
}

